package com.dong.c01_bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <h1></h1>
 *   telnet 后  ctrl+[ 进入会话  send ...
 * @author : dzj
 * @create: 2020-03-17 18:24
 */
public class BIOServer {
    // 1 创建线程池
    //2. 如果有客户端连接 则使用线程阈值通信
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while(true) {
            final Socket socket = serverSocket.accept();
            System.out.println("连接一个客户端");
            threadPool.execute(()-> {
                //可以和客户端通讯
                handle(socket);
            });
        }
    }
    //通讯方法
    public static void handle(Socket socket) {
        InputStream inputStream=null;
        try {
            byte[] bytes = new byte[1024];
             inputStream = socket.getInputStream();
             int len=0;
             while((len=inputStream.read(bytes))!=-1) {
                 Thread thread = Thread.currentThread();
                 System.out.println(new String(bytes,0,len)+"thread: "+thread.getName());

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                System.out.println("关闭client的链接");
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
